package com.share.device.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.mapper.RegionMapper;
import com.share.device.service.IRegionService;
import com.share.system.api.domain.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IRegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {


    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<Region> treeSelect(String parentCode) {
        List<Region> regionList = regionMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, parentCode));
        if (!CollectionUtils.isEmpty(regionList)) {
            regionList.forEach(item -> {
                long count = regionMapper.selectCount(new LambdaQueryWrapper<Region>().eq(Region::getParentCode, item.getCode()));
                if (count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }
            });
        }
        return regionList;
    }

    @Override
    public String getNameByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return "";
        }
        Region region = regionMapper.selectOne(new LambdaQueryWrapper<Region>().eq(Region::getCode,code).select(Region::getName));
        if(null != region) {
            return region.getName();
        }
        return "";
    }

    /**
     * 获取表的行数
     */
    @Override
    public int getTableCount() {
        return Math.toIntExact(regionMapper.selectCount(null));
    }

    @Override
    public List<Region> getAllRegion(int page, int pageSize) {
        Page<Region> regionPage = new Page<>(page, pageSize);
        QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<>();
        return regionMapper.selectPage(regionPage,regionQueryWrapper).getRecords();
    }
}
